﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JiaBao.Core.Data
{
    public class DataSettingsManager
    {
        #region CONST
        protected const char separator = ':';
        protected const string filename = "Setting.txt";
        #endregion

        #region Fields

        #endregion

        #region 属性

        #endregion

        #region Ctor

        #endregion

        #region 方法

        /// <summary>
        /// 读取并解析配置文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public virtual DataSettings LoadSettings(string filePath = null)
        {
            if (String.IsNullOrEmpty(filePath))
            {
                filePath = Path.Combine(CommonHelper.MapPath("/App_Data/"), filename);
            }

            if (File.Exists(filePath))
            {
                var text = File.ReadAllText(filePath);
                return ParseSetting(text);
            }
            return new DataSettings();
        }

        /// <summary>
        /// 保存配置到文件
        /// </summary>
        /// <param name="settings"></param>
        public virtual void SaveSettings(DataSettings settings)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");

            Directory.CreateDirectory(CommonHelper.MapPath("/App_Data/"));
            var filePath = Path.Combine(CommonHelper.MapPath("/App_Data/"), filename);
            if (!File.Exists(filePath))
            {
                using (File.Create(filePath)) { }

            }
            var text = ComposeSettings(settings);
            File.WriteAllText(filePath, text);

        }

        #endregion

        #region 内部方法

        /// <summary>
        /// 解析配置字符串
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        protected virtual DataSettings ParseSetting(string text)
        {
            var shellSettings = new DataSettings();
            if (String.IsNullOrEmpty(text))
                return shellSettings;

            var settings = new List<string>();
            using (var reader = new StringReader(text))
            {
                string str;
                while ((str = reader.ReadLine()) != null)
                {
                    settings.Add(str);
                }
            }
            foreach (var setting in settings)
            {
                var separatorIndex = setting.IndexOf(separator);
                if (separatorIndex == -1)
                    continue;
                string key = setting.Substring(0, separatorIndex).Trim();
                string value = setting.Substring(separatorIndex + 1).Trim();
                switch (key)
                {
                    case "DataProvider":
                        shellSettings.DataProvider = value;
                        break;

                    case "DataConnectionString":
                        // Data Source=47.97.121.106;Initial Catalog=DS;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=12345@sas
                        shellSettings.DataConnectionString = value;
                        var sp = value.Split(';');
                        foreach (var s in sp)
                        {
                            var p = s.Split('=');
                            switch (p[0])
                            {
                                case "Data Source":
                                    shellSettings.Server =p[1].Trim();
                                    break;

                                case "Initial Catalog":
                                    shellSettings.DataBase = p[1].Trim();
                                    break;

                                case "User ID":
                                    shellSettings.Uid = p[1].Trim();
                                    break;

                                case "Password":
                                    shellSettings.Pwd = p[1].Trim();
                                    break;

                                default:
                                    break;
                            }
                        }
                        break;

                    default:
                        shellSettings.RawDataSettings.Add(key, value);
                        break;
                }
            }
            return shellSettings;
        }

        /// <summary>
        /// DataSettings转字符串
        /// </summary>
        /// <param name="settings"></param>
        /// <returns></returns>
        protected virtual string ComposeSettings(DataSettings settings)
        {
            if (settings == null)
                return "";

            return string.Format("DataProvider: {0}{2}DataConnectionString: {1}{2}",
                                    settings.DataProvider,
                                    settings.DataConnectionString,
                                    Environment.NewLine);
        }

        #endregion

    }
}
